package com.example.demo.datasource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = MybatisConfig.PACKAGE, sqlSessionTemplateRef = "housekeepingSqlSessionTemplate")
public class MybatisConfig {
    public final static String PACKAGE = "com.example.demo.mapper";

    static final String MAPPER_LOCATION = "classpath:mapper/**/*.xml";
    @Bean(name = "housekeepingSqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Autowired DynasticDataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MybatisConfig.MAPPER_LOCATION));
        return bean.getObject();
    }

    @Bean(name = "housekeepingTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Autowired DynasticDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "housekeepingSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(
            @Qualifier("housekeepingSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
